package com.gmcc.bi.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class RedisConnector {

	private static JedisCluster cluster;
	private static Set<HostAndPort> clusterNodes;
	RedisConnector() {
		connectRedis();

	}

	private void connectRedis() {
		clusterNodes = new HashSet<HostAndPort>();
		clusterNodes.add(new HostAndPort("182.61.40.138", 7000));
		clusterNodes.add(new HostAndPort("182.61.40.138", 7001));
		clusterNodes.add(new HostAndPort("182.61.40.138", 7002));
		clusterNodes.add(new HostAndPort("182.61.40.138", 7003));
		clusterNodes.add(new HostAndPort("182.61.40.138", 7004));
		clusterNodes.add(new HostAndPort("182.61.40.138", 7005));
//		clusterNodes.add(new HostAndPort("172.18.0.23", 6370));
//		clusterNodes.add(new HostAndPort("172.18.0.24", 6380));
//		clusterNodes.add(new HostAndPort("172.18.0.25", 6390));
//		clusterNodes.add(new HostAndPort("172.18.0.23", 6391));
//		clusterNodes.add(new HostAndPort("172.18.0.24", 6371));
//		clusterNodes.add(new HostAndPort("172.18.0.25", 6381));

		cluster = new JedisCluster(clusterNodes);

	}

	public  void putData(String key,String data) {
			try {
				if (cluster == null) {
					cluster = new JedisCluster(clusterNodes);

				}
					String result = cluster.set(key,data);
					System.out.println("put:" + key + "    " + "value:"+ data+"	result="+result);
			} catch (Exception e) {

				e.printStackTrace();
			}

	}
	
	public  void putDataMap(String key,Map<String, String> map ) {
			try {
				if (cluster == null) {
					cluster = new JedisCluster(clusterNodes);

				} 
					String hmset = cluster.hmset(key, map);
					System.out.println("put:" + key + "    " + "value:"+ map.toString()+"	result="+hmset);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public  Map<String, String> getDataMap(String key) {
		Map<String, String> data = new HashMap<String, String>();
		try {
			if (cluster == null) {
				cluster = new JedisCluster(clusterNodes);
			} 
			data = cluster.hgetAll(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
}
	
	public  void  close() throws IOException {
		cluster.close();
	}
	
	public void del(String key){
		try {
			if (cluster == null) {
				cluster = new JedisCluster(clusterNodes);
			} 
			if (StringUtils.isNotBlank(key)) {
				cluster.del(key);
				System.out.println("redis删除"+key+"成功");
			}else{
				System.out.println("redis_key为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		
		
		Map<String, String> dataMap = RedisClusterUtil.getInstance().getDataMap("aa");
		System.out.println(dataMap.toString());
	}
}
